package com.gigi.service.manual;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gigi.entity.BlogShiqinEntity;
import com.gigi.entity.CommentShiqinEntity;
import com.gigi.entity.LikeCommentShiqinEntity;
import com.gigi.entity.UserShiqinEntity;
import com.gigi.enums.ErrorCodeEnum;
import com.gigi.enums.YesOrNoEnum;
import com.gigi.mapper.generated.CommentShiqinMapper;
import com.gigi.model.CommentDO;
import com.gigi.model.ListCommentRequest;
import com.gigi.service.generated.BlogShiqinService;
import com.gigi.service.generated.CommentShiqinService;
import com.gigi.service.generated.LikeCommentShiqinService;
import com.gigi.service.generated.UserShiqinService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CommentManageService {

    private final CommentShiqinService commentShiqinService;
    private final CommentShiqinMapper commentShiqinMapper;
    private final UserShiqinService userShiqinService;
    private final LikeCommentShiqinService likeCommentShiqinService;
    private final BlogShiqinService blogShiqinService;

    public CommentManageService(CommentShiqinService commentShiqinService, CommentShiqinMapper commentShiqinMapper,
                                UserShiqinService userShiqinService, LikeCommentShiqinService likeCommentShiqinService,
                                BlogShiqinService blogShiqinService) {
        this.commentShiqinService = commentShiqinService;
        this.commentShiqinMapper = commentShiqinMapper;
        this.userShiqinService = userShiqinService;
        this.likeCommentShiqinService = likeCommentShiqinService;
        this.blogShiqinService = blogShiqinService;
    }

    /**
     * 保存接口
     *
     * @param request
     * @return
     */
    public Response save(CommentDO request) {
        CommentShiqinEntity target = new CommentShiqinEntity();
        target.setContent(request.getContent());
        target.setTime(LocalDateTime.now());
        target.setUserId(request.getUserId());
        target.setReplyUserName(request.getReplyUserName());
        target.setReplyContent(request.getReplyContent());
        target.setParentId(request.getParentId());
        target.setBlogId(request.getBlogId());
        if (!commentShiqinService.save(target)) {
            return Response.buildFailure(ErrorCodeEnum.SAVE_FAILED.getErrCode(), ErrorCodeEnum.SAVE_FAILED.getErrDesc());
        }
        return Response.buildSuccess();
    }

    /**
     * 列表接口
     *
     * @return
     */
    public MultiResponse<CommentDO> list(ListCommentRequest request) {
        if (request.getPageNum() < 1) {
            request.setPageNum(1);
        }
        if (request.getPageSize() < 1) {
            request.setPageSize(10);
        }

        LambdaQueryWrapper<CommentShiqinEntity> wrapper = new LambdaQueryWrapper<CommentShiqinEntity>()
                .eq(Objects.nonNull(request.getBlogId()), CommentShiqinEntity::getBlogId, request.getBlogId())
                .orderByDesc(CommentShiqinEntity::getId);

        List<CommentShiqinEntity> list;
        int total;

        if (YesOrNoEnum.YES.getCode().equals(request.getIfByPage())) {
            Page<CommentShiqinEntity> page = new Page<>(request.getPageNum(), request.getPageSize());
            Page<CommentShiqinEntity> commentPage = commentShiqinMapper.selectPage(page, wrapper);
            list = commentPage.getRecords();
            total = (int) commentPage.getTotal();
        } else {
            list = commentShiqinService.list(wrapper);
            total = list.size();
        }
        if (CollUtil.isEmpty(list)) {
            return MultiResponse.of(Collections.emptyList(), 0);
        }

        List<CommentDO> commentDOS = new ArrayList<>();
        for (CommentShiqinEntity e : list) {
            LambdaQueryWrapper<LikeCommentShiqinEntity> wrapper1 = new LambdaQueryWrapper<LikeCommentShiqinEntity>()
                    .eq(LikeCommentShiqinEntity::getCommentId, e.getId());
            List<LikeCommentShiqinEntity> likeCommentList = likeCommentShiqinService.list(wrapper1);
            UserShiqinEntity user = userShiqinService.getById(e.getUserId());
            BlogShiqinEntity blog = blogShiqinService.getById(e.getBlogId());

            if (ObjectUtils.allNotNull(user, blog)) {
                CommentDO commentDO = new CommentDO();
                commentDO.setId(e.getId());
                commentDO.setContent(e.getContent());
                commentDO.setUserId(e.getUserId());
                commentDO.setUserName(user.getName());
                commentDO.setUserPic(user.getPic());
                commentDO.setReplyUserName(e.getReplyUserName());
                commentDO.setReplyContent(e.getReplyContent());
                commentDO.setParentId(e.getParentId());
                commentDO.setTimeStr(DateUtil.format(e.getTime(), DatePattern.NORM_DATETIME_PATTERN));
                commentDO.setBlogId(e.getBlogId());
                commentDO.setBlogTitle(blog.getTitle());
                if (CollUtil.isNotEmpty(likeCommentList)) {
                    commentDO.setLikeCount((int) likeCommentList.stream().filter(i -> YesOrNoEnum.NO.getCode().equals(i.getType())).count());
                    commentDO.setHateCount((int) likeCommentList.stream().filter(i -> YesOrNoEnum.YES.getCode().equals(i.getType())).count());
                }
                commentDOS.add(commentDO);
            }
        }

        if (YesOrNoEnum.NO.getCode().equals(request.getIfByPage())) {
            List<CommentDO> rootList = commentDOS.stream().filter(i -> i.getParentId() == 0).collect(Collectors.toList());
            rootList.forEach(e -> {
                e.setChildren(commentDOS.stream().filter(i -> e.getId().equals(i.getParentId())).collect(Collectors.toList()));
            });
            return MultiResponse.of(rootList, total);
        }

        return MultiResponse.of(commentDOS, total);
    }

    /**
     * 删除接口
     *
     * @param id
     * @return
     */
    public Response delete(Long id) {
        if (!commentShiqinService.removeById(id)) {
            return Response.buildFailure(ErrorCodeEnum.DELETE_FAILED.getErrCode(), ErrorCodeEnum.DELETE_FAILED.getErrDesc());
        }
        LambdaQueryWrapper<CommentShiqinEntity> wrapper = new LambdaQueryWrapper<CommentShiqinEntity>()
                .eq(CommentShiqinEntity::getParentId, id);
        List<CommentShiqinEntity> list = commentShiqinService.list(wrapper);
        if (CollUtil.isNotEmpty(list)) {
            List<Long> ids = list.stream().map(e -> e.getId()).collect(Collectors.toList());
            if (!commentShiqinService.removeByIds(ids)) {
                return Response.buildFailure(ErrorCodeEnum.DELETE_FAILED.getErrCode(), ErrorCodeEnum.DELETE_FAILED.getErrDesc());
            }
        }
        return Response.buildSuccess();
    }

}
